package com.example.ymm.util;

import com.alibaba.fastjson.JSONObject;
import com.cmb.xft.open.api.BaseReqInf;
import com.cmb.xft.open.api.HttpResponseData;
import com.cmb.xft.open.api.XftOpenApiReqClient;
import com.example.ymm.exception.YmException;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithID;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.util.*;

@Slf4j
public class HttpClientUtil {



    //Http协议GET请求
    public static String httpGet(String url, JSONObject param,JSONObject header) {
        String result = "";
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (UtilValidate.isNotEmpty(param)) {
                param.forEach((key, value) -> {
                    if(UtilValidate.isNotEmpty(value)){
                        uriBuilder.addParameter(key, value.toString());
                    }
                });
            }
            //初始化HttpClient
            CloseableHttpClient httpClient = createSSLClientDefault();
            //创建HttpGet
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Content-Type","application/json");
            httpGet.addHeader("Accept-Charset","utf-8");
            httpGet.addHeader("Cookie","language=zh_CN");
            httpGet.addHeader("language","zh_CN");
            if(UtilValidate.isNotEmpty(header)){
                header.forEach((k,v)->{
                    httpGet.addHeader(k,v.toString());
                });
            }
            //发起请求，获取response对象
            CloseableHttpResponse response = httpClient.execute(httpGet);
            //获取请求状态码
            //response.getStatusLine().getStatusCode();
            //获取返回数据实体对象
            HttpEntity entity = response.getEntity();
            //转为字符串
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;

    }

    //Http协议Post请求 发送对象
    public static String httpPost(String url, JSONObject json,JSONObject header) {
        String result = "";
        try {
            //初始HttpClient
            CloseableHttpClient httpClient = createSSLClientDefault();
            //创建Post对象
            HttpPost httpPost = new HttpPost(url);
            //设置Content-Type
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.addHeader("Accept-Charset","utf-8");
            httpPost.addHeader("Cookie","language=zh_CN");
            httpPost.addHeader("language","zh_CN");
            if(UtilValidate.isNotEmpty(header)){
                header.forEach((k,v)->{
                    httpPost.addHeader(k,v.toString());
                });
            }
            //写入JSON数据
            httpPost.setEntity(new StringEntity(json.toJSONString()));
            //发起请求，获取response对象
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //获取请求码
            //response.getStatusLine().getStatusCode();
            //获取返回数据实体对象
            HttpEntity entity = response.getEntity();
            //转为字符串
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println("---postresult:"+result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        return result;

    }

    //Http协议Post请求 发送数组
    public static String httpPostStr(String url, String arrStr,JSONObject header) {
        String result = "";
        try {
           // log.info("--header:"+header);

            //初始HttpClient
            CloseableHttpClient httpClient =createSSLClientDefault();

            //创建Post对象
            HttpPost httpPost = new HttpPost(url);
            //设置Content-Type
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.addHeader("Accept-Charset","utf-8");
            httpPost.addHeader("Cookie","language=zh_CN");
            httpPost.addHeader("language","zh_CN");
            if(UtilValidate.isNotEmpty(header)){
                header.forEach((k,v)->{
                    if(UtilValidate.isNotEmpty(v)){
                        httpPost.addHeader(k,v.toString());
                    }

                });
            }
            //写入JSON数据
            httpPost.setEntity(new StringEntity(arrStr));
            //发起请求，获取response对象
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //获取请求码
            //response.getStatusLine().getStatusCode();
            //获取返回数据实体对象
            HttpEntity entity = response.getEntity();
            //转为字符串
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println("---postresult:"+result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        return result;

    }


    //Http协议Put请求
    public static String httpPut(String url, JSONObject json,JSONObject header) {
        String result = "";
        try {
            //初始HttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建Post对象
            HttpPut httpPut = new HttpPut(url);
//            HttpPost httpPost = new HttpPost(url);
            //设置Content-Type
            httpPut.setHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept-Charset","utf-8");
            httpPut.addHeader("Cookie","language=zh_CN");
            httpPut.addHeader("language","zh_CN");
            if(UtilValidate.isNotEmpty(header)){
                header.forEach((k,v)->{
                    httpPut.addHeader(k,v.toString());
                });
            }
            //写入JSON数据
            httpPut.setEntity(new StringEntity(json.toJSONString()));
            //发起请求，获取response对象
            CloseableHttpResponse response = httpClient.execute(httpPut);
            //获取请求码
            //response.getStatusLine().getStatusCode();
            //获取返回数据实体对象
            HttpEntity entity = response.getEntity();
            //转为字符串
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println("---postresult:"+result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        return result;

    }

    //Http协议Put请求
    public static String httpDelete(String url, JSONObject json,JSONObject header) {
        String result = "";
        try {
            //初始HttpClient
            CloseableHttpClient httpClient = createSSLClientDefault();

            URIBuilder uriBuilder = new URIBuilder(url);

            //写入JSON数据
            if (UtilValidate.isNotEmpty(json)) {
                json.forEach((key, value) -> {
                    uriBuilder.addParameter(key, value.toString());
                });
            }
            //创建Post对象
            HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
//            HttpPost httpPost = new HttpPost(url);
            //设置Content-Type
            httpDelete.setHeader("Content-Type", "application/json");
            httpDelete.addHeader("Accept-Charset","utf-8");
            httpDelete.addHeader("Cookie","language=zh_CN");
            httpDelete.addHeader("language","zh_CN");
            if(UtilValidate.isNotEmpty(header)){
                header.forEach((k,v)->{
                    httpDelete.addHeader(k,v.toString());
                });
            }
            //发起请求，获取response对象
            CloseableHttpResponse response = httpClient.execute(httpDelete);
            //获取请求码
            //response.getStatusLine().getStatusCode();
            //获取返回数据实体对象
            HttpEntity entity = response.getEntity();
            //转为字符串
            result = EntityUtils.toString(entity, "UTF-8");
            System.out.println("---postresult:"+result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        return result;

    }


    //Https协议Get请求
    public static String httpsGet(String url) throws Exception {
        CloseableHttpClient hp = createSSLClientDefault();
        HttpGet hg = new HttpGet(url);
        CloseableHttpResponse response = hp.execute(hg);
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity, "UTF-8");
        hp.close();
        return content;
    }

    //Https协议Post请求
    public static String httpsPost(String url, String json) throws Exception {

        CloseableHttpClient hp = createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(json));
        CloseableHttpResponse response = hp.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity, "UTF-8");
        hp.close();
        return content;
    }


    public static CloseableHttpClient createSSLClientDefault() throws Exception {
        //如果下面的方法证书还是不过，报错的话试试下面第二种
        /* SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
        //信任所有
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        return true;
        }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();*/

        // 创建信任所有证书的SSL上下文
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (certificate, authType) -> true)
                .build();

        // 创建SSL连接工厂
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext, NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

    }






}